import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../store/user'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'users',
        name: 'UserList',
        component: () => import('../views/users/List.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'notices',
        name: 'NoticeList',
        component: () => import('../views/notices/List.vue'),
        meta: { requiresAuth: true }
      },
      { 
        path: 'files',
        name: 'FileList',
        component: () => import('../views/files/List.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'courses',
        name: 'CourseList',
        component: () => import('../views/courses/List.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'courses/:id',
        name: 'CourseDetail',
        component: () => import('../views/courses/Detail.vue'),
        meta: { requiresAuth: true }
      },
    ]
  }
]

const router = createRouter({
  history: createWebHistory('/chance/manage/'),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  
  if (requiresAuth && !userStore.isLoggedIn) {
    next({ name: 'Login' })
  } else {
    next()
  }
})

export default router